﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#region using for special implements
using System.Runtime.Serialization.Json;
using System.IO;
#endregion using for special implements

namespace Com.ProjectA.Utility
{
    public class JSONHelper
    {
        /// <summary>
        /// JSON Serialization
        /// <para>t: Input Type T</para>
        /// <para>Caution: Return JSON string, can be null if there is exceptions</para>
        /// </summary>
        /// <param name="t">Input Type T</param>
        /// <returns>JSON string. Caution: Can be null</returns>
        public static string JsonSerializer<T>(T t)
        {
            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, t);
                string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return jsonString;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// JSON Deserialization
        /// <para>jsonString: Input JSON string. This one must be not null</para>
        /// <para>return: Output Type T, can be emtpy elements when throws exception</para>
        /// </summary>
        /// <param name="jsonString">Input JSON string. This one must be not null</param>
        /// <returns>Output Type T, can be emtpy elements when throws exception</returns>
        public static T JsonDeserialize<T>(string jsonString)
        {
            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                T obj = (T)ser.ReadObject(ms);
                return obj;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
    }
}
